<?php
require_once(DIR_SYSTEM.'engine/restcontroller.php');

class ControllerRestAutoPurchase extends RestController {
    public function index() {
        return $this->orderedNums();
    }

    /*
     * 智能配货
     */
    public function aiPurchase() {

		$this->checkPlugin();
		$this->load->model('checkout/auto_purchase');

		$json = array('success' => true);

        $page = min(intval($this->request->get['page']), 1);
        $limit = intval($this->request->get['limit']);

        $results = $this->model_checkout_auto_purchase->getOrderedNums();
        $this->showProductInfo($results,$limit);

    }

    /*
     * 购买频次降序
     */
    public function orderedNums() {

		$this->checkPlugin();
		$this->load->model('checkout/auto_purchase');

		$json = array('success' => true);

        $page = min(intval($this->request->get['page']), 1);
        $limit = intval($this->request->get['limit']);

        $results = $this->model_checkout_auto_purchase->getOrderedNums();
        $this->showProductInfo($results,$limit);

    }

	 /*
     * 购买时间
     */
    public function orderedStamp() {

		$this->checkPlugin();
		$this->load->model('checkout/auto_purchase');

		$json = array('success' => true);

        $page = min(intval($this->request->get['page']), 1);
        $limit = intval($this->request->get['limit']);

        $results = $this->model_checkout_auto_purchase->getOrderedStamp();
        $this->showProductInfo($results,$limit);

    }

    /*
     * 商城销量降序
     */
    public function salesInMall() {

		$this->checkPlugin();
		$this->load->model('checkout/auto_purchase');

		$json = array('success' => true);

        $page = min(intval($this->request->get['page']), 1);
        $limit = intval($this->request->get['limit']);

        $results = $this->model_checkout_auto_purchase->getSalesInMall();
        $this->showProductInfo($results,$limit);

    }

    /*
     * 新品推荐
     */
    public function newArrival() {

		$this->checkPlugin();
		$this->load->model('checkout/auto_purchase');

		$page = min(intval($this->request->get['page']), 1);
    $limit = intval($this->request->get['limit']);

		$results = $this->model_checkout_auto_purchase->getNewArrival();
		$this->showProductInfo($results,$limit);

    }

    /*
     * 小程序智能配货
     */

	//获取筛选条件
	public function getSearchDefault(){

		$json['shopType'] = getShopType();
		$json['shelfType'] = getShelfType();
		$json['payGrade'] = getPayGrade();

		$this->load->model('tool/image');
		$this->load->model('checkout/auto_purchase');

		$json['category'] = $this->model_checkout_auto_purchase->getSolutionCategory();
		foreach($json['category'] as &$v){

			//增加品类货节
			$id = $v['cid'];
			$v['qty'] = $this->model_checkout_auto_purchase->getCategoryQty($id);

			//增加品类图片
			if ($v['cimage'] != null && file_exists(DIR_IMAGE . $v['cimage'])) {
                $image = $this->model_tool_image->resize($v['cimage'], 100, 100);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }
			$v['cimage'] = $image;

		}

		//获取品类各种条件下的货节
		$json['solutionQty'] = $this->getSolutionQty();

		$this->response->setOutput(json_encode($json));

	}

	//获取品类各种条件下的货节
	public function getSolutionQty(){
		$this->load->model('checkout/auto_purchase');
		$result = $this->model_checkout_auto_purchase->getSolutionQty();
		foreach($result as &$v){
			$v['solution_category'] = intval(trim(trim($v['solution_category']),","));
			$v['shelf_types'] = intval(trim(trim($v['shelf_types']),","));
			$v['length'] = intval($v['length']);
			$v['start'] = intval($v['start']);
			$v['end'] = intval($v['end']);
		}
		return $result;
	}



	//获取货架
	public function W_getShelf(){

	$requestjson = file_get_contents('php://input');
	$data = json_decode($requestjson, true);
    if(isset($data['shopid'])){
       $filter['shop_id'] = intval($data['shopid']);
    }
    if(isset($data['solutionId'])){
      $filter['solution_id'] = intval($data['solutionId']);
    }
    if(isset($data['template'])){
      $filter['template'] = intval($data['template']);
    }
    if(isset($data['shelfids'])){
      $filter['shelfids'] = $data['shelfids'];
      $filter['myshop'] = $data['myshop'];
    }
		$filter['customer_id'] = $data['customer_id'];
		$filter['shopType'] = is_numeric($data['shopType'])?$data['shopType']:-1;
		$filter['shelfType'] = is_numeric($data['shelfType'])?$data['shelfType']:-1;
		$filter['payGrade'] = is_numeric($data['payGrade'])?$data['payGrade']:-1;
		$filter['categoryList'] = json_decode($data['categoryList'], true);

		if(isset($data['page'])){
			$filter['page'] = $data['page'];
		}
		else{
			$filter['page'] = 1;
		}

		if(isset($data['limit'])){
			$filter['limit'] = $data['limit'];
		}
		else{
			$filter['limit'] = 20;
		}
      //var_dump($filter);
        $this->load->model('checkout/auto_purchase');
		$results = $this->model_checkout_auto_purchase->W_getShelf($filter);


		if($results){
			$this->formatShelf($results);
		}

	}

	//优化货架详细信息
	public function formatShelf($data){

		$this->load->model('tool/image');
		$this->load->model('checkout/auto_purchase');

		$json = array('success' => true);

		$shelfType = getShelfType();
		$payGrade = getPayGrade();
			$i = 0;
		foreach($data as $v){
			$i++;
			/*货架缩略图*/
		 if($v['cimage'] != null && file_exists(DIR_IMAGE . $v['cimage'])) {
               $image = $this->model_tool_image->resize($v['cimage'], 100, 100);
          }else{
               $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
          }

      if ($v['shelf_image'] != null && file_exists(DIR_UPLOAD . $v['shelf_image'])) {
               $shelfimage = "https://m.bhz360.com/system/storage/upload/".$v['shelf_image'];
          }else if($v['cimage'] != null && file_exists(DIR_IMAGE . $v['cimage'])){
                $shelfimage = $this->model_tool_image->resize($v['cimage'], 25, 25);
          }else{
                $shelfimage = $this->model_tool_image->resize('no_image.jpg', 25, 25);
          }
			/*货架缩略图*/

			/*货架商品详细*/
			$shelfProduct = array();
			$shelfProducts = $this->model_checkout_auto_purchase->getShelfProducts($v['shelf_id']);
			foreach($shelfProducts as $key => $v2){
				$shelfProduct[$key] = $this->getProductInfo($v2);
				if($shelfProduct[$key] != null){
					$shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
					$shelfProduct[$key]['shelf_id'] = $v['shelf_id'];
					$shelfProduct[$key]['shelf_x'] = $v2['layer_position'];
					$shelfProduct[$key]['shelf_y'] = $v2['shelf_layer'];
          $shelfProduct[$key]['shelf_product_id'] = $v2['shelf_product_id'];
				}
			}
			/*货架商品详细*/

			$shelf_name = $v['shelf_name'];
			$json['shelf'][] = array(
    				'shelf_id' => $v['shelf_id'],
    				'image' => $image,
            'shelfimage' => $shelfimage,
    				'name' => $shelf_name,
    				'category_id' => $v['category_id'],
    				'scount' => 1,
    				'shelfProduct' => array_values(array_filter($shelfProduct)), //去空数组重编index
			      'shelf_map_id' => $v['shelf_map_id'],
			      'neworder' => $v['neworder'],
			      'status' => $v['status'],

			);
		}


		$this->response->setOutput(json_encode($json));

	}
  //优化缓存获取货架(pages/customer/ai/shelf/shelf)
  public function WgetShelf(){

  $requestjson = file_get_contents('php://input');
  $data = json_decode($requestjson, true);
    if(isset($data['shopid'])){
       $filter['shop_id'] = intval($data['shopid']);
    }
    if(isset($data['solutionId'])){
      $filter['solution_id'] = intval($data['solutionId']);
    }
    if(isset($data['template'])){
      $filter['template'] = intval($data['template']);
    }
    if(isset($data['shelfids'])){
      $filter['shelfids'] = $data['shelfids'];
      $filter['myshop'] = $data['myshop'];
    }
    $filter['customer_id'] = $data['customer_id'];
    $filter['shopType'] = is_numeric($data['shopType'])?$data['shopType']:-1;
    $filter['shelfType'] = is_numeric($data['shelfType'])?$data['shelfType']:-1;
    $filter['payGrade'] = is_numeric($data['payGrade'])?$data['payGrade']:-1;
    $filter['categoryList'] = json_decode($data['categoryList'], true);

    if(isset($data['page'])){
      $filter['page'] = $data['page'];
    }
    else{
      $filter['page'] = 1;
    }

    if(isset($data['limit'])){
      $filter['limit'] = $data['limit'];
    }
    else{
      $filter['limit'] = 20;
    }
      //var_dump($filter);
    $this->load->model('checkout/auto_purchase');
    $results = $this->model_checkout_auto_purchase->W_getShelf($filter);

    //var_dump($results);die;
    if($results){
      $this->W_formatShelf($results);
    }

  }

  //优化缓存货架详细信息(pages/customer/ai/shelf/shelf)
  public function W_formatShelf($data){

    $this->load->model('tool/image');
    $this->load->model('checkout/auto_purchase');

    $json = array('success' => true);

    $shelfType = getShelfType();
    $payGrade = getPayGrade();
      $i = 0;
    foreach($data as $v){
      $i++;
      /*货架缩略图*/
     if($v['cimage'] != null && file_exists(DIR_IMAGE . $v['cimage'])) {
               $image = $this->model_tool_image->resize($v['cimage'], 100, 100);
          }else{
               $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
          }

      if ($v['shelf_image'] != null && file_exists(DIR_UPLOAD . $v['shelf_image'])) {
               $shelfimage = "https://m.bhz360.com/system/storage/upload/".$v['shelf_image'];
          }else if($v['cimage'] != null && file_exists(DIR_IMAGE . $v['cimage'])){
                $shelfimage = $this->model_tool_image->resize($v['cimage'], 25, 25);
          }else{
                $shelfimage = $this->model_tool_image->resize('no_image.jpg', 25, 25);
          }
      /*货架缩略图*/

      /*货架商品详细*/
      $shelfProduct = array();
      $shelfProducts = $this->model_checkout_auto_purchase->getShelfProducts($v['shelf_id']);
      foreach($shelfProducts as $key => $v2){
        $shelfProduct[$key] = $this->WgetProductInfo($v2);
        if($shelfProduct[$key] != null){
          $shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
          $shelfProduct[$key]['shelf_product_id'] = $v2['shelf_product_id'];
        }
      }
      /*货架商品详细*/

      $shelf_name = $v['shelf_name'];
      $json['shelf'][] = array(
            'shelf_id' => $v['shelf_id'],
            'image' => $image,
            'shelfimage' => $shelfimage,
            'name' => $shelf_name,
            'category_id' => $v['category_id'],
            'scount' => 1,
            'shelfProduct' => array_values(array_filter($shelfProduct)), //去空数组重编index
            'shelf_map_id' => $v['shelf_map_id'],
            'neworder' => $v['neworder'],
            'status' => $v['status'],
      );
    }
    $this->response->setOutput(json_encode($json));
  }
  //获取配置商品信息
  public function detailconfig(){
      $requestjson = file_get_contents('php://input');
      $data = json_decode($requestjson, true);
      $this->load->model('checkout/auto_purchase');
        /*货架商品详细*/
        //var_dump($data['shelf_id']);die;
      $shelfProduct = array();
      $shelfProducts = $this->model_checkout_auto_purchase->getShelfProducts($data['shelf_id']);
      //var_dump($shelfProducts);die;
      foreach($shelfProducts as $key => $v2){
        $shelfProduct[$key] = $this->getProductInfo($v2);
        if($shelfProduct[$key] != null){
          $shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
          $shelfProduct[$key]['shelf_id'] = $v['shelf_id'];
          $shelfProduct[$key]['shelf_x'] = $v2['layer_position'];
          $shelfProduct[$key]['shelf_y'] = $v2['shelf_layer'];
          $shelfProduct[$key]['shelf_product_id'] = $v2['shelf_product_id'];
        }
      }
      /*货架商品详细*/

      $shelf_name = $v['shelf_name'];
      $json['shelf'][] = array(
            'shelf_id' => $data['shelf_id'],
            'shelfProduct' => array_values(array_filter($shelfProduct)), //去空数组重编index
      );


    $this->response->setOutput(json_encode($json));



  }


  //获取单个商品的价格(pages/customer/ai/shelf/shelf)
   public function WgetProductInfo($data){
        $this->load->model('catalog/product');
        $retval = array();
        $id = $data['product_id'];
        $result = $this->model_catalog_product->getListProduct($id);

        if($result){
            $product = $result[0];

            $this->load->model('tool/image');
            $this->load->model('catalog/category');

            /*product image*/
            if ($product['image'] != null && file_exists(DIR_IMAGE . $product['image'])) {
                $image = $this->model_tool_image->resize($product['image'], 100, 100);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }
            /*product image*/

      /*市场价*/
            $price = $this->currency->restFormat($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $price_formated = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*市场价*/

      /*售价*/
            $sale_price = $this->currency->restFormat($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $sale_price_formated = $this->currency->format($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*售价*/

            /*特价*/
            if ((float)$product['special']) {
                $special = $this->currency->restFormat($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
                $special_formated = $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
            }
            /*特价*/
             $retval = array(
                'id' => $product['product_id'],
                'price' => $price,
                'price_formated' => $price_formated,
                'special' => $special ? $special : $sale_price,
                'special_formated'  => $special_formated ? $special_formated : $sale_price_formated,
                'sku' => $product['sku']
            );

            return $retval;

        }

    }

	//获取推荐商品
	public function getSearchProducts(){

		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);

		/*筛选条件*/
		if(isset($data['shelf_id'])){
			$filter['shelf_id'] = $data["shelf_id"];
		}

		if(isset($data['start'])){
			$filter['start'] = $data['start'];
		}
		else{
			$filter['start'] = 0;
		}

		if(isset($data['limit'])){
			$filter['limit'] = $data['limit'];
		}
		else{
			$filter['limit'] = 20;
		}

		if(isset($data['shelf_x'])){
			$shelf_x = $data['shelf_x'];
		}
		else{
			$shelf_x = 0;
		}

		if(isset($data['shelf_y'])){
			$shelf_y = $data['shelf_y'];
		}
		else{
			$shelf_y = 0;
		}

		if(isset($data['searchinput'])){
			$filter['searchinput'] = $data['searchinput'];
		}
		else{
			$filter['searchinput'] = "";
		}
		/*筛选条件*/

		$this->load->model('checkout/auto_purchase');
		$searchProducts = $this->model_checkout_auto_purchase->getSearchProducts($filter);

		$sp = array();
		foreach($searchProducts as $key => $v){
			$sp[$key] = $this->getProductInfo($v);
			if($sp[$key] != null){
				$sp[$key]['shelf_quantity'] = $v['minimum'];
				$sp[$key]['shelf_x'] = $shelf_x;
				$sp[$key]['shelf_y'] = $shelf_y;
				$sp[$key]['addnum'] = 0;
			}
		}

		$json['searchproducts'] = array_values(array_filter($sp)); //去空数组重编index

		$this->response->setOutput(json_encode($json));

	}

	//获取用户支付权限
	public function getPayCheck(){
		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);
		$customer_id = $data['customer_id'];

		$this->load->model('checkout/auto_purchase');
		$json['checkInfo'] = $this->model_checkout_auto_purchase->getPayCheck($customer_id);
		$this->response->setOutput(json_encode($json));
	}

	//获取用户默认地址
	public function getDefaultAddress(){

		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);
		$customer_id = $data['customer_id'];
		$this->load->model('checkout/auto_purchase');
		$json['sendAddress'] = $this->model_checkout_auto_purchase->getDefaultAddress($customer_id);
		$this->response->setOutput(json_encode($json));

	}


	//获取用户所有可用地址
	public function getAllAddress(){
		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);
		$customer_id = $data['customer_id'];
		$this->load->model('checkout/auto_purchase');
		$json['addresslist'] = $this->model_checkout_auto_purchase->getAllAddress($customer_id);
		$this->response->setOutput(json_encode($json));
	}

	//获取支付方式
	public function getPayMethod(){
		$json['paymethod'] = getPayMethod();
		$this->response->setOutput(json_encode($json));
	}

	//保存覆盖模板
	public function editTemplate(){
		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);

		$filter['solution_id'] = $data['solution_id'];
		$filter['shelflist'] = $data['shelflist'];

		$this->load->model('checkout/auto_purchase');
		$result = $this->model_checkout_auto_purchase->editTemplate($filter);

		$json['result'] = $result;
		$this->response->setOutput(json_encode($json));

	}

  //保存模板通道过来的货架
  public function saveshelf(){
    $requestjson = file_get_contents('php://input');
    $data = json_decode($requestjson, true);
   // var_dump($data);die;
    $filter['customer_id'] = $data['customer_id'];
    $filter['shelf_types'] = 0;
    $filter['shop_types'] = 0;
    $filter['pay_grades'] = 0;
    $filter['shop_id'] = $data['shop_id'];
   //var_dump($filter);die;
    $this->load->model('checkout/auto_purchase');
    if($data['cname']){
        $filter['shelf_name'] = $data['cname'];
        $filter['shelf_image'] = $data['cimage'];
        $filter['category_id'] = "855";
        $result = $this->model_checkout_auto_purchase->savecustomshelf($filter);
    }else{
        $filter['category_id'] = $data['category'];
        $filter['shelflist'] = $data['shelflist'];
        $result = $this->model_checkout_auto_purchase->saveshelf($filter);
    }
    $json['result'] = $result;
    $this->response->setOutput(json_encode($json));

  }

	//保存添加模板
	public function addTemplate(){

		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);

		$filter['solution_name'] = $data['solution_name'];
		$filter['customer_id'] = $data['customer_id'];

		$solution = $data['solution'];
		if(isset($solution['payGrade']) && $solution['payGrade'] != 'undefined'){
			$filter['pay_grades'] = $solution['payGrade'];
		}
		else{
			$filter['pay_grades'] = "";
		}

		if(isset($solution['shelfType']) && $solution['shelfType'] != 'undefined'){
			$filter['shelf_types'] = $solution['shelfType'];
		}
		else{
			$filter['shelf_types'] = "";
		}

		if(isset($solution['shopType']) && $solution['shopType'] != 'undefined'){
			$filter['shop_types'] = $solution['shopType'];
		}
		else{
			$filter['shop_types'] = "";
		}

		$filter['categoryList'] = $solution['categoryList'];
		$filter['shelflist'] = $data['shelflist'];

		$this->load->model('checkout/auto_purchase');
		$json['solution_id'] = $this->model_checkout_auto_purchase->addTemplate($filter);

		$this->response->setOutput(json_encode($json));

	}

	//立即购买放入商城购物车
	public function toBuy(){

		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);

		$add['customer_id'] = $data['customer_id'];
		$add['products'] = $data['products'];

		$this->load->model('checkout/auto_purchase');
		$json['test'] = $this->model_checkout_auto_purchase->addCart($add);

		$this->response->setOutput(json_encode($json));

	}

	//返回显示商品页面
	public function showProductInfo($data,$limit){

		$json = array('success' => true);

		$n = 1;
		foreach($data as $v){
			if($n > $limit){
				break;
			}
			$temp = $this->getProductInfo($v);
			if($temp){
				$json['products'][] = $temp;
			}
			$n++;
		}
		$this->response->setOutput(json_encode($json));

	}

	//获取单个商品必要信息
    public function getProductInfo($data){

        $this->load->model('catalog/product');

        $retval = array();
        $id = $data['product_id'];
        $result = $this->model_catalog_product->getListProduct($id);

        if($result){

            $product = $result[0];

            $this->load->model('tool/image');
            $this->load->model('catalog/category');


            /*product image*/
            if ($product['image'] != null && file_exists(DIR_IMAGE . $product['image'])) {
                $image = $this->model_tool_image->resize($product['image'], 100, 100);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }
            /*product image*/

			     /*市场价*/
            $price = $this->currency->restFormat($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $price_formated = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*市场价*/

			     /*售价*/
            $sale_price = $this->currency->restFormat($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $sale_price_formated = $this->currency->format($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*售价*/

            /*特价*/
            if ((float)$product['special']) {
                $special = $this->currency->restFormat($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
                $special_formated = $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
            }
            /*特价*/
              $sku = $product['sku'];
             $sku = substr($sku,-6);
            $retval = array(
                'id' => $product['product_id'],
                'name' => $product['name'],
                'image' => $image,
        				'product_class1' => $product['product_class1'],
        				'product_class2' => $product['product_class2'],
        				'product_class3' => $product['product_class3'],
        				'pov_code' => $product['product_code']."0",
        				'minimum' => $product['minimum'] ? $product['minimum'] : 1,
        				'price' => $price,
                'price_formated' => $price_formated,
                'special' => $special ? $special : $sale_price,
                'special_formated'  => $special_formated ? $special_formated : $sale_price_formated,
                'sku' => $sku
            );

            return $retval;

        }

    }


    //保存购买的方案、货架、货架商品信息，汇总货架商品信息后返回
    protected function _solutionSave($data, $now) {
        $shelfIds = array();
        $products = array();
        $this->load->model('ssl/solution');
		$categoryName = $this->model_ssl_solution->getCategoryName($data['buylist']);
        $newSolutionInfo = array(
            'customer_id' => $data['customerId'],
            'solution_name' => date('Y-m-d').$categoryName,
            'date_added' => $now,
        );
        $newSolutionId = $this->model_ssl_solution->addNew($newSolutionInfo);
        $modifySolutionInfo = array();
        $this->load->model('ssl/shelf');
        foreach ($data['buylist'] as $k=>$shelfInfo) {
            $newShelfInfo = array(
                'solution_id' => $newSolutionId,
                'customer_id' => $data['customerId'],
                'shelf_name' => $shelfInfo['name'],
                'parent_shelf' => $shelfInfo['shelf_id'],
				        'shelf_category' => $shelfInfo['category_id'],
                'date_added' => $now,
            );
            $newShelfId = $this->model_ssl_shelf->addNew($newShelfInfo);
            $shelfIds[] = $newShelfId;
            $modifySolutionInfo['shelf_length'] += 1;
            $modifyShelfInfo = array();
            foreach ($shelfInfo['shelfProduct'] as $kk=>$productInfo) {
                $newShelfProductInfo = array(
                    'shelf_id' => $newShelfId,
                    'product_id' => $productInfo['id'],
                    'product_code' => $productInfo['pov_code'],
                    'shelf_layer' => $productInfo['shelf_y'],
                    'layer_position' => $productInfo['shelf_x'],
                    'show_qty' => $productInfo['shelf_quantity'],
                    'min_order_qty' => $productInfo['minimum'],
                    'date_added' => $now,
                );
                if ($this->model_ssl_shelf->addNewProduct($newShelfProductInfo)){
                    $modifyShelfInfo['shelf_class1'][$productInfo['product_class1']] = 1;
                    $modifyShelfInfo['shelf_class2'][$productInfo['product_class2']] = 1;
                    $modifyShelfInfo['shelf_class3'][$productInfo['product_class3']] = 1;
                    $modifySolutionInfo['shelf_class1'][$productInfo['product_class1']] = 1;
                    $modifySolutionInfo['shelf_class2'][$productInfo['product_class2']] = 1;
                    $modifySolutionInfo['shelf_class3'][$productInfo['product_class3']] = 1;
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['price'] = $productInfo['special'];
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['buy_qty'] += $productInfo['shelf_quantity'];
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['shelf_info'] = array(
    						          'S'=>$newShelfId,
                        	'Y'=>$productInfo['shelf_y'],
                        	'X'=>$productInfo['shelf_x'],
                        	'qty' => $productInfo['shelf_quantity'],
                    );
                }
            }
            foreach ($modifyShelfInfo as $kk=>$value) {
                $modifyShelf[$kk] = ','.implode(',', array_keys($value)).',';
            }
            $this->model_ssl_shelf->modifyByPK($newShelfId, $modifyShelf);
        }
        foreach ($modifySolutionInfo as $k=>$value) {
            if (is_array($value)) {
                $modifySolution[$k] = ','.implode(',', array_keys($value)).',';
            }else{
                $modifySolution[$k] = $value;
            }
        }
        $this->model_ssl_solution->modifyByPK($newSolutionId, $modifySolution);
        return compact('shelfIds', 'products');
    }

    protected function _shelfOrderSave($data, $shelfIds, $products, $now) {
        $this->load->model('ssl/order');
        $this->load->model('ssl/shelf_order');
        $shelfOrderInfo = array(
            'customer_id' => $data['customerId'],
            'shelf_ids' => implode(',', $shelfIds),
            'add_name' => $data['sendaddress']['name'],
            'add_tel' => $data['sendaddress']['tel'],
            'add_country' => $data['sendaddress']['country'],
            'add_city' => $data['sendaddress']['city'],
            'add_zone' => $data['sendaddress']['zone'],
            'add_address' => $data['sendaddress']['address'],
            'add_company' => $this->model_ssl_order->getCompanyByAddressId($data['sendaddress']['address_id']),
            'paycode' => $data['paycode'],
            'order_price' => $data['allprice'],
            'date_added' => $now,
            'date_customer_check' => $now,
            'date_user_check' => $now,//绕开业务员补货单认证，客户提交直接发送到order表
        );
        $shelfOrderId = $this->model_ssl_shelf_order->addNew($shelfOrderInfo);
        // var_dump($products);die;
        foreach ($products as $unique=>$info) {
            list($productId, $productCode) = explode('_', $unique);
            $shelfOrderProductInfo = array(
                'shelf_order_id' => $shelfOrderId,
                'customer_id' => $data['customerId'],
                'product_id' => $productId,
                'product_code' => $productCode,
                'shelf_info' => json_encode($info['shelf_info']),
                'price' => $info['price'],
                'buy_qty' => $info['buy_qty'],
            );
            $this->model_ssl_shelf_order->addNewProduct($shelfOrderProductInfo);
        }
        return $shelfOrderId;
    }

    protected function _addNewSystemTaskByShelfOrderId($shelfOrderId, $now) {
        $this->load->model('ssl/shelf_order');
        $this->load->model('ssl/system_task');
        extract($this->model_ssl_shelf_order->getCustomerInfoByShelfOrderId($shelfOrderId));
        if (0 == $orderId) {
            if ($dateCustomerCheck && $dateUserCheck) {//复制补货单到订单，不创建任务
                $orderId = $this->_cpShelfOrderToOrder($shelfOrderId, $now);
                $shelfOrderInfo = array(
                    'order_id' => $orderId,
                );
                $this->model_ssl_shelf_order->modifyByPK($shelfOrderId, $shelfOrderInfo);
                //修改货架状态为已入场
                $this->model_ssl_shelf_order->solutionEnter($shelfOrderId);
            }else if ($dateCustomerCheck){//创建业务员确认补货单任务
                $params = array(
                    'shelfOrderId' => $shelfOrderId,
                );
                $systemTaskInfo = array(
                    'task_type' => 'shelf',
                    'task_expire' => '-1',
                    'refer_pk' => $customerId,
                    'params' => json_encode($params),
                    'operate_type' => 'user',
                    'operate_pk' => $userId,
                    'action' => 'shelfOrderCheck',
                    'date_added' => $now,
                );
                $this->model_ssl_system_task->addNew($systemTaskInfo);
            }else if ($dateUserChecked) {//创建客户确认补货单任务
                $params = array(
                    'shelfOrderId' => $shelfOrderId,
                );
                $systemTaskInfo = array(
                    'task_type' => 'shelf',
                    'task_expire' => '-1',
                    'refer_pk' => $customerId,
                    'params' => json_encode($params),
                    'operate_type' => 'customer',
                    'operate_pk' => $customerId,
                    'action' => 'shelfOrderCheck',
                    'date_added' => $now,
                );
                $this->model_ssl_system_task->addNew($systemTaskInfo);
            }
        }else{//已存在关联订单

        }
    }
      protected function W_getPaymentMethod($code) {
        $payMethodList = getPayMethod();
        //var_dump($payMethodList);die;
        foreach ($payMethodList as $v) {
            if ($v['code'] == $code) {
                return $v['name'];
            }
        }
    }

    protected function _cpShelfOrderToOrder($data,$shelfIds,$now,$comment) {
        $this->load->model('ssl/shelf_order');
        $this->load->model('ssl/order');
        /* 订单主表 */
       $sql = "SELECT `customer_group_id`,`fullname`,`email`,`telephone`,`fax`,`user_id`,`logcenter_id`,`shop_id` FROM `".DB_PREFIX."customer` WHERE `customer_id`='".$data['customerId']."'";
        $q = $this->db->query($sql);
        $customerGroupId = intval($q->row['customer_group_id']);
        $fullName = trim($q->row['fullname']);
        $email = trim($q->row['email']);
        $telephone = trim($q->row['telephone']);
        $fax = trim($q->row['fax']);
        $userId = intval($q->row['user_id']);
        $logcenterId = intval($q->row['logcenter_id']);
        $shop_id =  intval($q->row['shop_id']);
        $paymentMethod = $this->W_getPaymentMethod($data['paycode']);
        $countryId = $this->model_ssl_order->getCountryIdByName($data['sendaddress']['country']);
        $zoneId = $this->model_ssl_order->getZoneIdByName($countryId, $data['sendaddress']['zone']);
        $cityId = $this->model_ssl_order->getCityIdByName($zoneId, $data['sendaddress']['city']);

        $orderInfo = array(
            'store_id' => '0',
            'store_name' => '百货栈',
            'store_url' => 'http://m.bhz360.com/',
            'customer_id' => $data['customerId'],
            'customer_group_id' => $customerGroupId,
            'fullname' => $fullName,
            'email' => $email,
            'telephone' => $telephone,
            'fax' => $fax,
            'payment_fullname' => $data['sendaddress']['name'],
            'payment_company' =>  $this->model_ssl_order->getCompanyByAddressId($data['sendaddress']['address_id']),
            'payment_address' => $data['sendaddress']['address'],
            'payment_city' => $data['sendaddress']['city'],
            'payment_city_id' => $cityId,
            'payment_postcode' => '',
            'payment_country' => $data['sendaddress']['country'],
            'payment_country_id' => $countryId,
            'payment_zone' => $data['sendaddress']['zone'],
            'payment_zone_id' => $zoneId,
            'payment_address_format' => '',
            'payment_method' => $paymentMethod,
            'payment_code' => $data['paycode'],
            'shipping_fullname' => $data['sendaddress']['name'],
            'shipping_company' => $this->model_ssl_order->getCompanyByAddressId($data['sendaddress']['address_id']),
            'shipping_address' => $data['sendaddress']['address'],
            'shipping_city' => $data['sendaddress']['city'],
            'shipping_city_id' => $cityId,
            'shipping_postcode' => '',
            'shipping_country' => $data['sendaddress']['country'],
            'shipping_country_id' => $countryId,
            'shipping_zone' => $data['sendaddress']['zone'],
            'shipping_zone_id' => $zoneId,
            'shipping_address_format' => '',
            'shipping_method' => '免运费',
            'shipping_code' => 'free.free',
            'shipping_telephone' => $data['sendaddress']['tel'],
            'total' => $data['allprice'],
            'ori_total' => $data['allprice'],
            'order_status_id' => 20,
            'affiliate_id' => 0,
            'commission' => 0,
            'marketing_id' => 0,
            'tracking' => '',
            'language_id' => 1,
            'currency_id' => 4,
            'currency_code' => 'CNY',
            'currency_value' => 1,
            'date_added' => $now,
            'logcenter_id' => $logcenterId,
            'is_pay' => $ifPay,
            'recommend_usr_id' => $userId,
            'shelf_order_id' => implode(',', $shelfIds),
            'shelf_order_type' => 2,
        );

         $orderId = $this->model_ssl_order->addNew($orderInfo);

        if ($orderId){
            $c = 1;
            foreach ($shelfIds as $key => $value) {
               $this->db->query("UPDATE shelf set neworder=".$orderId." where shelf_id=".$value);
             }
              foreach ($data['buylist'] as $key => $value) {
                  foreach ($value['shelfProduct'] as $k => $v) {
                        $value['shelfProduct'][$k]['shelf_id'] = $value['shelf_id'];
                        $array[]=$value['shelfProduct'][$k];
                  }

              }

            foreach ($array as $info) {
                  //var_dump($info);die;
                /* 订单商品表 */
                $this->load->model('ssl/product');
                $productInfo = $this->model_ssl_product->getByPK($info['id']);
                // var_dump($productInfo);die;
                $images = $this->model_ssl_product->getimages($info['id']);
                $orderProductInfo = array(
                    'order_id' => $orderId,
                    'product_id' => $info['id'],
                    'shelf_id' => $info['shelf_id'],
                    'product_code' => $productInfo['sku'],
                    'name' => $productInfo['name'],
                    'model' => $productInfo['model'],
                    'quantity' => $info['shelf_quantity'],
                    'price' => $info['special'],
                    'pay_price' => $info['special'],
                    'total' => $info['special']*$info['shelf_quantity'],
                    'pay_total' => $info['special']*$info['shelf_quantity'],
                    'tax' => 0,
                    'reward' => 0,
                    'vendor_id' => 0,
                    'order_status_id' => 0,
                    'commission' => 0,
                    'store_tax' => 0,
                    'vendor_tax' => 0,
                    'vendor_total' => 0,
                    'vendor_paid_status' => 0,
                    'title' => '',
                    'ship_status' => 0,
                    'shipped_time' => '0000-00-00 00:00:00',
                    'lack_quantity' => $info['shelf_quantity'],
                    'order_ids' => $c,
                );
                //var_dump($orderProductInfo);die;
                $orderProductId = $this->model_ssl_order->addNewProduct($orderProductInfo);
               $shop_productId = $this->db->query("SELECT shop_product_id  from `shop_product` where product_id=".$info['id']." AND shop_id=".$shop_id)->row;
                if(empty($shop_productId)){
                  // 商铺产品信息注册
                 $newproductinfo['product_class1'] = $productInfo['product_class1'];
                 $newproductinfo['product_class2'] = $productInfo['product_class2'];
                 $newproductinfo['product_class3'] = $productInfo['product_class3'];
                  $length = $this->db->query("SELECT count(*) as `long` from `shop_product` where shop_id=".$shop_id)->row;

                  $length = intval($length['long'])+1;
                  $shop_basic_code = $shop_id.'_'.$length;
                  $newproductinfo['shop_basic_code'] = $shop_basic_code;//商品编码
                  $newproductinfo['sku'] = $productInfo['sku'];//sku
                  $newproductinfo['price'] = $info['price'];//新品价格
                  $newproductinfo['sale_price'] = $info['price'];//优惠价
                  $newproductinfo['date_added'] = date("y-m-d h:i:s",time());//添加时间
                  $newproductinfo['shop_id'] = $shop_id;//商铺id
                  $newproductinfo['shelf_id'] = $info['shelf_id'];//货架id
                  $newproductinfo['name'] = $productInfo['name'];//新品名称
                  $newproductinfo['image'] = $productInfo['image'];//主图
                  $newproductinfo['description'] = $productInfo['description'];//主图
                  $newproductinfo['product_id'] =  $info['id'];//主图
                  $shopproductId = M('shop_product')->add($newproductinfo);
                   M('shelf_product')->where(array('shelf_product_id'=>$info['shelf_product_id']))->save(array('shop_product_id'=>$shopproductId));
                  if($images){
                      foreach ($images as $key => $value) {
                        $image['product_id'] = $info['id'];
                        $image['image'] = $value['image'];
                        $image['shop_product_id'] =  $shopproductId;
                        M('shop_product_image')->add($image);
                      }
                   }
                   $shop_product_code = $shop_basic_code.'_1';
                    $option['shop_product_code'] = $shop_product_code;
                    $option['name'] = "通用";
                    $option['shop_product_id'] = $shopproductId;
                    $options = M('shop_product_option')->add($option);
                }else{
                     M('shelf_product')->where(array('shelf_product_id'=>$info['shelf_product_id']))->save(array('shop_product_id'=>$shop_productId['shop_product_id']));
                }


                 $c++;
                /* 订单选项表 */
                $orderOptionInfo = array(
                    'order_id' => $orderId,
                    'order_product_id' => $orderProductId,
                    'product_option_id' => $productInfo['productOptionId'],
                    'product_option_value_id' => $productInfo['productOptionValueId'],
                    'name' => $productInfo['optionName'],
                    'value' => $productInfo['optionValueName'],
                    'type' => $productInfo['optionType'],
                );
                $this->model_ssl_order->addNewInTable($orderOptionInfo, 'order_option');
            }
            /* 订单日志表 */
            $orderHistoryInfo = array(
                'order_id' => $orderId,
                'order_status_id' => 20,
                'date_added' => $now,
            );
            $this->model_ssl_order->addNewInTable($orderHistoryInfo, 'order_history');
            /* 订单总价表 */
            $orderTotalInfo = array(
                'order_id' => $orderId,
                'code' => 'sub_total',
                'title' => '小计',
                'value' => $shelfOrderInfo['order_price'],
                'sort_order' => '1',
            );
            $this->model_ssl_order->addNewInTable($orderTotalInfo, 'order_total');
            /* 订单总价表 */
            $orderTotalInfo = array(
                'order_id' => $orderId,
                'code' => 'total',
                'title' => '总计',
                'value' => $shelfOrderInfo['order_price'],
                'sort_order' => '100',
            );
            $this->model_ssl_order->addNewInTable($orderTotalInfo, 'order_total');
            //把客户修改为货架客户
        }
         M('customer')->where(array('customer_id'=>$shelfOrderCustomerInfo['customerId']))->save(array('is_shelf_customer'=>1));

        return $orderId;
    }

    protected function _getPaymentMethod($code) {
        $payMethodList = getPayMethod();
        foreach ($payMethodList as $v) {
            if ($v['code'] == $code) {
                return $v['name'];
            }
        }
    }

	//获取知识分类
	public function getKnowCategory(){

		$this->load->model('checkout/auto_purchase');
		$json['category'] = $this->model_checkout_auto_purchase->getSolutionCategory();

		//锅具放第一个
		$guo = array();
		foreach($json['category'] as $key=>$v){
			if($v['cid'] == 780){
				$guo = $v;
				unset($json['category'][$key]);
			}
		}
		array_unshift($json['category'],$guo);

		$this->response->setOutput(json_encode($json));

	}

	//绑定二维码
	public function concatCode(){

		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);
    $time = date("Y-m-d H:i:s");
		$filter['shelf_map_id'] = $data['shelf_map_id'];
		$filter['shelf_id'] = $data['shelf_id'];
    $sql=$this->db->query("UPDATE shelf set date_map='".$time."' where shelf_id=".$filter['shelf_id']);
		$this->load->model('checkout/auto_purchase');
		$this->model_checkout_auto_purchase->concatCode($filter);

	}

	//获取筛选货架分类
	public function getClassBar(){
		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);

		$allclass = $data['allclass'];

		$filter['classbar'] = $data['classbar'];
		$this->load->model('checkout/auto_purchase');

		$cb1[] = array(
			'category_id' => 'all',
			'name' => '全部',
			'count' => count($allclass)
		);

		$cb2 = $this->model_checkout_auto_purchase->getClassBar($filter);

		foreach($cb2 as &$v){
			$v['count'] = array_count_values($allclass)[$v['category_id']];
		}

		$json['classbar'] = array_merge($cb1,$cb2);

		$this->response->setOutput(json_encode($json));
	}

	//通过id删除方案--------------
	public function delSolutionById(){
		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);

		$id = $data['solution_id'];
		$this->load->model('checkout/auto_purchase');
		$this->model_checkout_auto_purchase->delSolutionById($id);
	}

	//货架层页面内保存商品---------------------
	public function saveShelfProduct(){

		$requestjson = file_get_contents('php://input');
		$data = json_decode($requestjson, true);

		$filter['shelf_id'] = $data['shelf_id'];
		$filter['shelflist'][0] = $data['shelflist'];
		$filter['solution_id'] = $data['shop'];

		$this->load->model('checkout/auto_purchase');
		$result = $this->model_checkout_auto_purchase->saveShelfProduct($filter);

		$json['result'] = $result;
		$this->response->setOutput(json_encode($json));

	}



  //货架层页面内保存商品
  public function saveShelfProductinfo(){

    $requestjson = file_get_contents('php://input');
    $data = json_decode($requestjson, true);

    $filter['shelf_id'] = $data['shelf_id'];
    $filter['shelflist'][0] = $data['shelflist'];
    $filter['shop_id'] = $data['shop_id'];

    $this->load->model('checkout/auto_purchase');
    $result = $this->model_checkout_auto_purchase->saveShelfProductinfo($filter);

    $json['result'] = $result;
    $this->response->setOutput(json_encode($json));

  }
  //为了返回货架id修改缓存数据
  public function W_saveShelfProductinfo(){

    $requestjson = file_get_contents('php://input');
    $data = json_decode($requestjson, true);

    $filter['shelf_id'] = $data['shelf_id'];
    $filter['shelflist'][0] = $data['shelflist'];
    $filter['shop_id'] = $data['shop_id'];

    $this->load->model('checkout/auto_purchase');
    $result = $this->model_checkout_auto_purchase->W_saveShelfProductinfo($filter);

    $json['result'] = $result;
    $this->response->setOutput(json_encode($json));

  }
  //删除货架id
  public function delShelfId(){
    $requestjson = file_get_contents('php://input');
    $data = json_decode($requestjson, true);

    $id = $data['shelf_id'];
    $this->load->model('checkout/auto_purchase');
    $this->model_checkout_auto_purchase->delShelfinfo($id);
  }


  //首次补货
  public function W_addToOrderFirst(){
        $now = date('Y-m-d H:i:s');
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        if(isset($data['comment'])){
            $comment=$data['comment'];
        }else{
            $comment="无留言";
        }

        if($data['template']==1){
           extract($this->W_solutionSave($data, $now));
        }else{
          foreach ($data['buylist'] as $key => $value) {
              $shelfIds[]=$value['shelf_id'];
          }
            // $products = $this->W_getproducts($data);
        }
       // $shelfOrderId = $this->_shelfOrderSave($data, $shelfIds, $products, $now);
        //客户提交补货单后，需要业务员线下确认，通过后提交成系统后台订单，进入发货流程。
       $arr= $this->W_addNewSystemTaskByShelfOrderId($data,$now,$shelfIds,$comment);
        //$orderId = $this->_cpShelfOrderToOrder($shelfOrderId);
        // var_dump($arr);die;
        $json['success'] = true;
        $this->response->setOutput(json_encode($json));
  }

    //保存购买的方案、货架、货架商品信息，汇总货架商品信息后返回
    protected function W_solutionSave($data, $now) {
        $shelfIds = array();
        $products = array();
        $this->load->model('ssl/solution');
    $categoryName = $this->model_ssl_solution->getCategoryName($data['buylist']);
        // $newSolutionInfo = array(
        //     'customer_id' => $data['customerId'],
        //     'solution_name' => date('Y-m-d').$categoryName,
        //     'date_added' => $now,
        // );
        // $newSolutionId = $this->model_ssl_solution->addNew($newSolutionInfo);
        $modifySolutionInfo = array();
        $this->load->model('ssl/shelf');
        foreach ($data['buylist'] as $k=>$shelfInfo) {
            $newShelfInfo = array(
                'solution_id' => 0,
                'customer_id' => $data['customerId'],
                'shelf_name' => $shelfInfo['name'],
                'parent_shelf' => $shelfInfo['shelf_id'],
                'shelf_category' => $shelfInfo['category_id'],
                'date_added' => $now,
            );
            $newShelfId = $this->model_ssl_shelf->addNew($newShelfInfo);
            $shelfIds[] = $newShelfId;
            $modifySolutionInfo['shelf_length'] += 1;
            $modifyShelfInfo = array();
            foreach ($shelfInfo['shelfProduct'] as $kk=>$productInfo) {
                $newShelfProductInfo = array(
                    'shelf_id' => $newShelfId,
                    'product_id' => $productInfo['id'],
                    'product_code' => $productInfo['pov_code'],
                    'shelf_layer' => $productInfo['shelf_y'],
                    'layer_position' => $productInfo['shelf_x'],
                    'show_qty' => $productInfo['shelf_quantity'],
                    'min_order_qty' => $productInfo['minimum'],
                    'date_added' => $now,
                );
                if ($this->model_ssl_shelf->addNewProduct($newShelfProductInfo)){
                    $modifyShelfInfo['shelf_class1'][$productInfo['product_class1']] = 1;
                    $modifyShelfInfo['shelf_class2'][$productInfo['product_class2']] = 1;
                    $modifyShelfInfo['shelf_class3'][$productInfo['product_class3']] = 1;
                    $modifySolutionInfo['shelf_class1'][$productInfo['product_class1']] = 1;
                    $modifySolutionInfo['shelf_class2'][$productInfo['product_class2']] = 1;
                    $modifySolutionInfo['shelf_class3'][$productInfo['product_class3']] = 1;
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['price'] = $productInfo['special'];
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['buy_qty'] += $productInfo['shelf_quantity'];
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['shelf_info'] = array(
                'S'=>$newShelfId,
                          'Y'=>$productInfo['shelf_y'],
                          'X'=>$productInfo['shelf_x'],
                          'qty' => $productInfo['shelf_quantity'],
                    );
                }
            }
            foreach ($modifyShelfInfo as $kk=>$value) {
                $modifyShelf[$kk] = ','.implode(',', array_keys($value)).',';
            }
            $this->model_ssl_shelf->modifyByPK($newShelfId, $modifyShelf);
        }
        // foreach ($modifySolutionInfo as $k=>$value) {
        //     if (is_array($value)) {
        //         $modifySolution[$k] = ','.implode(',', array_keys($value)).',';
        //     }else{
        //         $modifySolution[$k] = $value;
        //     }
        // }
        // $this->model_ssl_solution->modifyByPK($newSolutionId, $modifySolution);

        return compact('shelfIds', 'products');
    }

    public function W_getproducts($data){
      //var_dump($data);die;
       $products = array();
      foreach ($data['buylist'] as $k=>$shelfInfo) {
            foreach ($shelfInfo['shelfProduct'] as $kk=>$productInfo) {

                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['price'] = $productInfo['special'];
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['buy_qty'] += $productInfo['shelf_quantity'];
                    $products[$productInfo['id'].'_'.$productInfo['pov_code']]['shelf_info'] = array(
                          'S'=>$productInfo['shelf_id'],
                          'Y'=>$productInfo['shelf_y'],
                          'X'=>$productInfo['shelf_x'],
                          'qty' => $productInfo['shelf_quantity'],
                    );
                }
            }

        return $products;
    }

     protected function W_addNewSystemTaskByShelfOrderId($data, $now,$shelfIds,$comment) {
        $this->load->model('ssl/shelf_order');
        $this->load->model('ssl/system_task');
        // extract($this->model_ssl_shelf_order->getCustomerInfoByShelfOrderId($shelfOrderId));

        // if (0 == $orderId) {

            // if ($dateCustomerCheck && $dateUserCheck) {//复制补货单到订单，不创建任务

                $orderId = $this->_cpShelfOrderToOrder($data,$shelfIds,$now,$comment);
                // $shelfOrderInfo = array(
                //     'order_id' => $orderId,
                // );
                //$this->model_ssl_shelf_order->modifyByPK($shelfOrderId, $shelfOrderInfo);
                //修改货架状态为已入场
               $shelfEnter= $this->model_ssl_shelf_order->shelfEnter($shelfIds);

        //     }else if ($dateCustomerCheck){//创建业务员确认补货单任务

        //         $params = array(
        //             'shelfOrderId' => $shelfOrderId,
        //         );
        //         $systemTaskInfo = array(
        //             'task_type' => 'shelf',
        //             'task_expire' => '-1',
        //             'refer_pk' => $customerId,
        //             'params' => json_encode($params),
        //             'operate_type' => 'user',
        //             'operate_pk' => $userId,
        //             'action' => 'shelfOrderCheck',
        //             'date_added' => $now,
        //         );
        //         $this->model_ssl_system_task->addNew($systemTaskInfo);
        //     }else if ($dateUserChecked) {//创建客户确认补货单任务

        //         $params = array(
        //             'shelfOrderId' => $shelfOrderId,
        //         );
        //         $systemTaskInfo = array(
        //             'task_type' => 'shelf',
        //             'task_expire' => '-1',
        //             'refer_pk' => $customerId,
        //             'params' => json_encode($params),
        //             'operate_type' => 'customer',
        //             'operate_pk' => $customerId,
        //             'action' => 'shelfOrderCheck',
        //             'date_added' => $now,
        //         );
        //         $this->model_ssl_system_task->addNew($systemTaskInfo);
        //     }
        // }else{//已存在关联订单
        // }
    }

   //获取模板方案信息2018.5.23
    public function getresult(){
      $this->load->model('wxapp/point');
      $data = $this->model_wxapp_point->getresult();

      $this->load->model('checkout/auto_purchase');
      foreach ($data as $key => $value) {
          $data[$key]['product'] = $this->model_checkout_auto_purchase->getproduct_id($value['solution_id']);
          //var_dump($this->model_checkout_auto_purchase->getproduct_id($value['solution_id']));die;
      }

      $arr=[];
        $this->load->model('tool/image');
        foreach ($data as $key => $value) {
           if ($value['image'] != null && file_exists(DIR_IMAGE . $value['image'])) {
                $value['image'] = $this->model_tool_image->resize($value['image'], 100, 100);
            } else {
                $value['image'] = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }

          foreach ($value['product'] as $k => $v) {
                $value['product'][$k]['product_id'] =  $this->simplifyWgetProductInfo($v);
          }
              $arr[]=$value;
        }

        foreach ($arr as $key => $value) {
          foreach ($value['product'] as $k => $v) {
            $value['product'][$k]['price']=$value['product'][$k]['product_id']['price'];
            $value['length'] = $value['product'][$k]['length'];
            $value['product'][$k]['special']=$value['product'][$k]['product_id']['special'];
            unset($value['product'][$k]['product_id']);
            unset($value['solution_category']);
          }
           $array[]=$value;
        }
        //var_dump($array);die;
         $this->response->setOutput(json_encode($array));
    }

    //简化获取单个商品的价格
   public function simplifyWgetProductInfo($data){
        $this->load->model('catalog/product');
        $retval = array();
        $id = $data['product_id'];
        $result = $this->model_catalog_product->simplifygetListProduct($id);
        if($result){
            $product = $result[0];
            $this->load->model('catalog/category');


      /*市场价*/
            $price = $this->currency->restFormat($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $price_formated = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*市场价*/

      /*售价*/
            $sale_price = $this->currency->restFormat($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $sale_price_formated = $this->currency->format($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*售价*/

            /*特价*/
            if ((float)$product['special']) {
                $special = $this->currency->restFormat($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
                $special_formated = $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
            }
            /*特价*/


             $retval = array(
                'price' => $price,
                'price_formated' => $price_formated,
                'special' => $special ? $special : $sale_price,
                'special_formated'  => $special_formated ? $special_formated : $sale_price_formated,
            );

            return $retval;

        }

    }
    //获取筛选货架大厅分类
  public function FiltergetClassBar(){
    $requestjson = file_get_contents('php://input');
    $data = json_decode($requestjson, true);

    $allclass = $data['allclass'];

    $filter['classbar'] = $data['classbar'];
    $this->load->model('checkout/auto_purchase');

    $cb1[] = array(
      'category_id' => 'all',
      'name' => '品类',
      'count' => count($allclass)
    );

    $cb2 = $this->model_checkout_auto_purchase->getClassBar($filter);
    foreach($cb2 as &$v){
      $v['count'] = array_count_values($allclass)[$v['category_id']];
    }

    $json['classbar'] = array_merge($cb1,$cb2);

    $this->response->setOutput(json_encode($json));
  }
  //获取方案下货架信息
  public function solutionshelf(){
       $requestjson = file_get_contents('php://input');
       $data = json_decode($requestjson, true);
       $this->load->model('checkout/auto_purchase');
      $results = $this->model_checkout_auto_purchase->solutionshelf($data);
      //var_dump($results);die;
      if($results){
        $this->WXT_formatShelf($results);
      }
  }

  //货架大厅货架详细信息
  public function WXT_formatShelf($data){
    $this->load->model('tool/image');
    $this->load->model('checkout/auto_purchase');

    $json = array('success' => true);

    $i = 0;
    foreach($data as $v){
      $i++;

      if ($v['shelf_image'] != null && file_exists(DIR_UPLOAD . $v['shelf_image'])) {
               $shelfimage = "https://m.bhz360.com/system/storage/upload/".$v['shelf_image'];
          }else{
                $shelfimage = $this->model_tool_image->resize('no_image.jpg', 25, 25);
         }
      /*货架缩略图*/

      /*货架商品详细*/
      $shelfProduct = array();
      $shelfProducts = $this->model_checkout_auto_purchase->getShelfProducts($v['shelf_id']);
      foreach($shelfProducts as $key => $v2){
        $shelfProduct[$key] = $this->WgetProductInfo($v2);

        if($shelfProduct[$key] != null){
          $shelfProduct[$key]['shelf_quantity'] = $v2['show_qty'];
        }
      }
      /*货架商品详细*/
      $shelf_name = $v['shelf_name'];
      $json['shelf'][] = array(
            'shelf_id' => $v['shelf_id'],
            'shelfimage' => $shelfimage,
            'name' => $shelf_name,
            'shelfProduct' => array_values(array_filter($shelfProduct)), //去空数组重编index
      );
    }
    $this->response->setOutput(json_encode($json));
  }

  //获取货架信息并将其复制到对应消费者名下
  public function  gainshelf(){
       $requestjson = file_get_contents('php://input');
       $data = json_decode($requestjson, true);
       $this->load->model('checkout/auto_purchase');
       $results = $this->model_checkout_auto_purchase->allshelf($data['solutionid']);
       foreach ($results as $key => $value) {
          $value['customer_id'] = $data['customer_id'];
          $value['shop_id'] = $data['shop_id'];
          $array[]=$value;
       }
       $this->model_checkout_auto_purchase->WXT_addShelf($array);

  }


}
